<?php


namespace App\Http\Controllers\Admin;
use App\Exports\RecommendExport;
use App\Models\Recommend;
use Dingo\Api\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class RecommendController extends BaseController
{

    public function index(Request $request) {
        $this->validate($request, [
            'status' => 'filled|in:0,1,2',
        ]);
        $status = $request->input('status');
        $company = $request->input('company');
        $position = $request->input('position');
        $is_export = $request->input('is_export', false);
        if ($is_export) {
            $limit = 50000;
        } else {
            $limit = $request->get('per_page',20);
        }

        $list = Recommend::withCertain('company', ['title'])
            ->withCertain('admin', ['username'])
            ->withCertain('position', ['position_title'])
            ->when($status, function ($q) use($status){
            $q->where('status', $status);
        })->when($company, function ($q) use($company) {
            $q->whereHas('company', function ($qc) use($company){
                $qc->where('title', 'like', '%'. $company . '%');
            });
        })->when($position, function ($q) use($position) {
            $q->whereHas('position', function ($qc) use($position){
                $qc->where('position_title', 'like', '%'. $position . '%');
            });
        })->orderBy("id", "desc")->paginate($limit);

        if ($is_export) {
            $res = $list->toArray();
            return Excel::download(new RecommendExport($res['data']),  "自荐列表.xlsx");
        }
        return $this->paginate($list);
    }



    public function setStatus(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $ids = $request->input("ids");
        $arr_id = explode(",", $ids);
        Recommend::whereIn('id', $arr_id)->update([
            'status' => Recommend::STATUS_FINISH,
            'admin_id' => $this->getUser()->id
        ]);
        return $this->success(['id' => $ids]);
    }


}

